// 标签页状态

import { setStorage } from '../utils/auth'

const actions = {}
const mutations = {
  // 初始化标签页
  INIT_PAGE_LIST(state, pageList) {
    state.pageList = pageList
  },
  // 添加标签页
  ADD_LABEL_PAGE(state, page) {
    page.isCurrent = true
    // 排他思想，让当前标签页为激活状态
    if (state.pageList.length) {
      state.pageList.forEach(item => (item.isCurrent = false))
      // 当前标签是否存在
      const isExist = state.pageList.some(item => item.path === page.path)
      if (isExist) {
        const index = state.pageList.findIndex(item => item.path === page.path)
        page.isCurrent = true
        state.pageList.splice(index, 1, page)
      } else {
        state.pageList.push(page)
      }
    } else {
      state.pageList.push(page)
    }
    // 存储到本地
    setStorage('pageList', state.pageList)
  },
  // 删除标签页
  DEL_LABEL_PAGE(state, index) {
    state.pageList.splice(index, 1)
    // 存储到本地
    setStorage('pageList', state.pageList)
  },
  // 激活页面
  ACTIVE_PAGE(state, page) {
    state.pageList.forEach(item => (item.isCurrent = false))
    const index = state.pageList.findIndex(item => item.path === page.path)
    state.pageList[index].isCurrent = true
    // 存储到本地
    setStorage('pageList', state.pageList)
  },
  // 关闭标签页 type1表示关闭其他，0表示关闭所有
  CLOSE(state, type) {
    console.log(type)
    if (type === 1) {
      const page = state.pageList.find(item => item.isCurrent === true)
      state.pageList = []
      state.pageList.push(page)
    } else {
      state.pageList = []
    }
    // 存储到本地
    setStorage('pageList', state.pageList)
  },
}
const state = {
  pageList: [], // 标签页数组
}

export default {
  namespaced: true,
  actions,
  mutations,
  state,
}
